import subprocess
import requests
import schedule
import time
import os
import logging
import datetime

# 配置日志记录
logging.basicConfig(filename='Rclone_SendDing.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def send_message(message):
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=d366870467b530aec25ef29d0be7345e19c44a6be8834518bba0ab9d5539c4f2'
    headers = {'Content-Type': 'application/json'}
    data = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    response = requests.post(webhook_url, json=data, headers=headers)
    if response.status_code == 200:
        print("消息发送成功")
    else:
        print("消息发送失败")


def sync_files():
    command = 'rclone sync oss:/obsbot-static-resource/website/obsbot-website/prod /data/oss/prod --track-renames --progress -v'
    logging.info("开始执行命令：" + command)

    # 使用subprocess运行rclone命令，并获取命令的输出
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = process.communicate()

    # 判断同步是否成功
    if process.returncode == 0:
        logging.info("命令执行完成")
        send_message("阿璨，oss更新完成")
    else:
        logging.error("命令执行失败：" + str(error))
        send_message("阿璨，oss更新失败")


def run_task():
    # 获取下一个凌晨时间
    now = datetime.datetime.now()
    tonight = now.replace(hour=0, minute=0, second=0) + datetime.timedelta(weeks=1)
    print(tonight)


    # 判断目标时间是否大于当前时间
    if tonight < now:
        tonight = now + datetime.datetime(days=2)
        tonight = tonight.replace(hour=0, minute=0, second=0)
        print("目标时间早于当前时间，将目标时间调整为当前时间的下一天的凌晨", tonight)


    # 获取目前时间还剩多少秒
    time_delta = (tonight - now).total_seconds()
    print(time_delta)

    schedule.every(time_delta).seconds.do(sync_files)
    # schedule.every().monday.do(sync_files)


run_task()

while True:
    try:
        schedule.run_pending()
        time.sleep(1)
    except Exception as e:
        logging.error("定时任务执行错误：" + str(e))
        send_message("Lin，定时任务执行过程中发生错误")

















